import db from '../mysql.js'

import {addUser, removeUser} from '../user.js'

export function login(req, res) {
    console.log('login', req.query, req.body)
	let {username, password} = req.body
	//数据库查询
	let sql =
		'SELECT u.user_id as userId, user_name as userName, password , GROUP_CONCAT(ur.role_id) as roleIds FROM sys_user u LEFT JOIN sys_user_role ur on (u.user_id = ur.user_id) where u.user_name = ? GROUP BY u.user_id';
	db.query(sql, [username], (err, result) => {
		let results = {}
		if (err) {
			console.log(err)
			results.msg = err;
			results.code = 500
		} else {
			results.code = 200
			if (result && result.length == 1 && result[0].password === password) {
				let token = 'BSC-USER-NJ-' + result[0].userId + '-' + new Date().getTime();
				let user = {
					...result[0],
					time: new Date().getTime(),
					token
				}
                addUser(token, user)
				results.data = user;
			} else {
				results.code = 500
				results.msg = '用户名或者密码错误'
			}
		}
		res.json(results)
	})
}

export function logout(req, res) {
    let token = req.get('Authorization');
	if (token) removeUser(token)
	res.json({
		code: 200,
		msg: '退出成功！'
	})
}